package com.seaside.park.api;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.seaside.common.bean.Result;
import com.seaside.park.bean.ParkingIncome;
import com.seaside.park.mapper.ParkingIncomeMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/api/income")
public class ParkingIncomeAPI {

    @Autowired
    private ParkingIncomeMapper parkingIncomeMapper;

    @PostMapping("/list")
    public Result<Double> countIncome(@RequestParam("placeId") int placeId,
                                      @RequestParam(value = "startTime", required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date startTime,
                                      @RequestParam(value = "endTime", required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date endTime) {
        // 检查车位号是否为空
        if (placeId == 0) {
            return Result.Error("车位号or车位ID不能为空");
        }

        QueryWrapper<ParkingIncome> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("place_id", placeId);

        // 设置开始时间
        if (startTime != null) {
            queryWrapper.ge("deal_time", startTime);
        }

        // 设置结束时间，如果没有提供，默认设置为结束日的最后一刻
        if (endTime == null) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(startTime != null ? startTime : new Date());
            calendar.set(Calendar.HOUR_OF_DAY, 23);
            calendar.set(Calendar.MINUTE, 59);
            calendar.set(Calendar.SECOND, 59);
            endTime = calendar.getTime();
        }
        queryWrapper.le("deal_time", endTime);

        // 执行查询
        List<ParkingIncome> incomes = parkingIncomeMapper.selectList(queryWrapper.orderByDesc("deal_time"));

        // 返回结果
        return Result.OK("查询成功", incomes);
    }


}
